import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useEmployeeStore = defineStore('employee', () => {
  const employees = ref([]);
  const loading = ref(false);

  const setEmployee = (tree) => {
    employees.value = [tree];
  };

  const clearEmployee = () => {
    employees.value = [];
  };

  const getEmployee = async() => {
    if (employees.value && employees.value.length) {
      return employees.value;
    }

    if (loading.value) {
      await sleep(100);
      return await getEmployee();
    }

    loading.value = true;
    const res = await api.post('/employee/queryTree').catch(() => {
      loading.value = false
    });
    if (res.code === "1") {
      loading.value = false;
      setEmployee(res.data);
      return employees.value;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return {
    getEmployee,
    clearEmployee
  };
});
